package com.sgl.gk.controller;

import cn.hutool.json.JSONUtil;
import com.fazecast.jSerialComm.SerialPort;
import com.sg.comm.common.Ret;
import com.sg.comm.serialport.SerialPortBatchDTO;
import com.sg.comm.serialport.SerialPortBatchReadReq;
import com.sg.comm.serialport.SerialPortDTO;
import com.sg.comm.service.SerialPortService;
import com.sgl.common.annotation.Log;
import com.sgl.common.core.controller.BaseController;
import com.sgl.common.core.domain.AjaxResult;
import com.sgl.common.core.page.TableDataInfo;
import com.sgl.common.enums.BusinessType;
import com.sgl.common.utils.ServletUtils;
import com.sgl.common.utils.StringUtils;
import com.sgl.gk.controller.vo.GkSparePartsVo;
import com.sgl.gk.controller.vo.ReworkVo;
import com.sgl.gk.domain.GkSetting;
import com.sgl.gk.domain.GkStationConfigurationValues;
import com.sgl.gk.mapper.GkSettingMapper;
import com.sgl.gk.mapper.GkStationConfigurationMapper;
import com.sgl.gk.mapper.GkStationConfigurationValuesMapper;
import com.sgl.gk.mapper.GkStationMapper;
import com.sgl.gk.scheduled.ScheduledTask;
import com.sgl.gk.service.GkSparePartsService;
import com.sgl.gk.tools.SerialTool;
import io.netty.handler.codec.http.HttpResponse;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author:xec
 * @date:2022/10/31 18:50
 *
 * 零部件表的controller
 **/
@RestController
@RequestMapping("/gk/spareparts")
public class GkSparePartsController extends BaseController {

    @Autowired
    GkSparePartsService gkSparePartsService;

//    @DubboReference(version = "1.0.0", url = "dubbo://192.168.0.107:20880", check = false)
    @DubboReference(version = "1.0.0", url = "dubbo://127.0.0.1:20880", check = false)
    private SerialPortService serialPortService;

    @Autowired
    GkSettingMapper gkSettingMapper;
    /**
     * 维修管理根据条码查询产品需要返修的零部件
     * @param barCode
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    public AjaxResult list(String barCode){
        if (barCode==null||barCode==""){
            return AjaxResult.success(getDataTable(new ArrayList<>()));
        }
        return gkSparePartsService.selectByBarCode(barCode);
    }

    /**
     * 更换零部件
     * @param gkSparePartsVo
     * @return
     */
    @ResponseBody
    @Log(title = "零部件",businessType = BusinessType.OTHER)
    @PostMapping("/replace")
    public AjaxResult replace(@RequestBody GkSparePartsVo gkSparePartsVo){
        if (StringUtils.isEmpty(gkSparePartsVo.getBeforePartCode())) {
            return AjaxResult.error("未找到需更换零部件");
        }
        return gkSparePartsService.replace(gkSparePartsVo);
    }

    /**
     * 单个零部件的更换历史
     * @param gkSparePartsVo
     * @return
     */
    @PostMapping("/listHistory")
    @ResponseBody
    public AjaxResult listHistory(@RequestBody ReworkVo reworkVo) {
        // sparePartsCode 未传
        if(ServletUtils.getParameter("pageSize")!=null&&ServletUtils.getParameter("pageNum")!=null){
            startPage();
        }
        List<GkSparePartsVo> gkSparePartsVos = gkSparePartsService.listHistory(reworkVo);
        TableDataInfo dataTable = getDataTable(gkSparePartsVos);
        Long total = gkSparePartsService.countBySparePartsCode(reworkVo);
        dataTable.setTotal(total);
        return AjaxResult.success(dataTable);
    }

    /**
     * 单个零部件的更换历史导出Excel
     * @param gkSparePartsVo
     * @return
     */
    @PostMapping("/export")
    @Log(title = "零部件",businessType = BusinessType.EXPORT)
    @ResponseBody
    public void export(ReworkVo reworkVo, HttpServletResponse response){
        gkSparePartsService.export(reworkVo,response);
    }

    /**
     * 获取扫码值
     * @return
     */
    @GetMapping("getBarCode")
    @ResponseBody
    public AjaxResult getBarCode(){
        Map<String,String> map = new HashMap<>();
        SerialPortBatchReadReq serialPortBatchReadReq = new SerialPortBatchReadReq();
        Ret<List<SerialPortBatchDTO>> listRet = null;
        List<GkSetting> list = gkSettingMapper.list();
        long nowTime = new Date().getTime();
        try {
            listRet=serialPortService.batchReadData(serialPortBatchReadReq);
        } catch (Exception e) {
           return  AjaxResult.error("扫码枪连接失败");
        }
        while ((listRet)!=null&&listRet.getData()!=null){
            try {
                listRet = serialPortService.batchReadData(serialPortBatchReadReq);
            } catch (Exception e) {
                return  AjaxResult.error("扫码枪连接失败");
            }
            for (GkSetting gkSetting : list) {
                List<SerialPortBatchDTO> data = listRet.getData();
                for (SerialPortBatchDTO datum : data) {
                    if (datum.getUid().equals(gkSetting.getSerialPortName())) {
                        if (!datum.getIsConn()){
                            return AjaxResult.error("扫码枪连接失败");
                        }
                        List<SerialPortDTO> dtoList = datum.getDtoList();
                        SerialPortDTO serialPortDTO = dtoList.stream().max(Comparator.comparing(SerialPortDTO::getLastModifyAt)).get();
                        if (serialPortDTO.getLastModifyAt()>=nowTime) {
                            map.put("barCode", serialPortDTO.getDataStr());
                            return AjaxResult.success(map);
                        }
                    }
                }
            }
            long time = new Date().getTime();
            if (time-nowTime>60000){
                return AjaxResult.error("扫码超时");
            }
        }
        return AjaxResult.error("扫码枪连接失败");
//        if (port==null){
//            for (SerialPort serialPort : serialPorts) {
//                if (serialPort.getSystemPortName().equals("COM4")) {
//                    serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);//设置超时
//                    serialPort.setRTS();//设置RTS。也可以设置DTR
//                    serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
//                    serialPort.setComPortParameters(115200, 8, 1, 0);
//                    if (!serialPort.isOpen()) {
//                        serialPort.openPort();
//                    }
//                    port = serialPort;
//                }
//            }
//        }else {
//            if (port.isOpen()) {
//                String msg = "";
//                while (true) {
//                    byte[] data = SerialTool.readFromPort(port);
//                    if (data != null) {
//                        msg = new String(data);
//                    }
//                    if (msg != "") {
//                        map.put("barCode", msg);
//                        ScheduledTask.isScanning = false;
//                        break;
//                    }
//                }
//            } else {
//                port.openPort();
//            }
//        }
    }
}
